//
//  HMComposeTableViewController.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/12.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

import SVProgressHUD


private let baseTag = 100

enum  ZQComposeType:Int{
    
    case Picture = 100
    case AtSome
    case Topic
    case Emoticon
    case More
    
   
}



class ZQComposeTableViewController: UIViewController {
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    
    //在外面判断是否为空
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.collectron.view.isHidden = collectron.contentImageArr.count == 0
        
    }
    
    //点击按钮
    @objc internal func toolBarButtonDidClick(btn: UIButton) {
       
        
        //拿到每一个控件的按钮.判断是哪一个
   let enumType = ZQComposeType.init(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            print("选择图片")
            
            collectron.addpicture(cell: nil)
            
        case .AtSome:
            print("@刚刚")
        case .Topic:
            print("话题")
        case .Emoticon:
            print("选择表情")
            //判断是否是第一相应者,如果不是让他变成第一相应这
            if !textView.isFirstResponder {
                
                textView.becomeFirstResponder()
            }

        //inputView 如果等于nil就弹出自定义键盘
            textView.inputView = ( textView.inputView == nil ? KeybordView : nil)
            
            //当inputView
            textView.reloadInputViews()
        case .More:
             print("更多")
        }
   
    }
    
    
    
    
    //懒加载自定义键盘
    lazy var KeybordView : HMEmoticonKeyboardView =  {
        
        let KeybordView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height:220))
        
        
       return KeybordView
    }()
    
    
    
    //发送按钮点击事件SAttachment
    func sendMessage(){
        var strM = String()
    textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: [], using:{ (dict,range,_) -> ()  in
        
        if let attachment  = dict["NSAttachment"] as? HMTextAttachment {
            
            //图片
            strM += attachment.chs ?? ""
            
            
        }else{
            //文字
            let sub = (self.textView.text as NSString).substring(with: range)
            
            strM += sub
            
        }
        
        
    })
   
        
        
        
        
        
//        var urlString = "https://api.weibo.com/2/statuses/update.json"
//        
//        let parameters = ["access_token" : ZQUserAccountViewModel.shared.access_token,
//                          "status" : textView.imageEmoticon2Chs()]
//        
//        if collectron.contentImageArr.count == 0{
//        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters , finished:{ (responseObject, error) -> () in
//            
//            if error == nil{
//                
//             SVProgressHUD.showError(withStatus: "发送微博失败")
//             return
//                
//            }
//            
//            SVProgressHUD.showInfo(withStatus: "发送成功了!")
//        })
//        
//        }else{
//            
//            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
//            
//            let imageDate = UIImagePNGRepresentation(self.collectron.contentImageArr.first!)
//            
//            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
//                
//                formdata.appendPart(withFileData: imageDate!, name: "pic", fileName: "hello", mimeType: "application/octet-stream")
//            }, progress: nil, success: { (_, resulthy) in
//                SVProgressHUD.showSuccess(withStatus: "发布成功")
//                
//            }, failure: { (_, error) in
//                SVProgressHUD.showError(withStatus: "发布失败")
//            })
//            
//            
//            
//        }
//        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
 
       self.view.backgroundColor = UIColor.white
        
        
      
        //通知
        notificationCenter()
        //导航栏控件
        naviItem()
        //输入文本
        textViewcLable()
        //toolBar
        showToolbar()
        
        
        addPicturController()
    }
    //注册通知
    func notificationCenter() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //选择表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(insetEmoticon(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
        
    }
    
    @objc private func insetEmoticon(n: Notification){
        
        //表情键盘插入
//        print(n)
        guard  let enmo = n.object as? HMEmoticon else {
            //删除按钮
            textView.deleteBackward()
            return
        }
//        textView.inputEmoticon(emoticon: enmo)
        //判断是不是Imoji表情
        if enmo.type == 1{
            
          
            textView.replace(textView.selectedTextRange!, withText: enmo.emojiStr ?? "")
            return
        }
        //表情图片 如果是表情图片就应该通过附件的类型实例化
        //是一个附件的类
       
        //通过附件类型实例化一个属性
      
        //1.实例化附件对象,将图片包装到附件对象中  public init(data contentData: Data?, ofType uti: String?)
        let attaciment = HMTextAttachment()
        
       attaciment.chs = enmo.chs
        //高度
        let lineHeight = textView.font?.lineHeight
         //设置字体大小
        attaciment.bounds = CGRect(x: 0, y: -4, width: lineHeight!, height: lineHeight!)
        
        
        attaciment.image = UIImage(named: enmo.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
        //2.通过附件对象实例化一个可变的属性字符串.后面要添加属性
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attaciment))
        
        imageText.addAttributes([NSFontAttributeName: textView.font!], range:NSRange(location: 0, length: 1) )
    
        
        
        //3.取得当前文本输入视图(可变的属性字符串)strM
        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
          //3.1替换属性文本之前光标显示的位置
          let range = textView.selectedRange
        //4.将imagetextt替换到str对应的光标位置
        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
        //5.将strM赋值给textView.attributedtext 
        
        textView.attributedText = strM
        //6 将光标赋值会来
        textView.selectedRange = NSRange(location: range.location + 1, length: 0)
        //代理监听不到自定义的附件
        textView.delegate?.textViewDidChange?(textView)
        
    }
    
    

    // 通知方法
    func keyboardChanged(n: Notification){
     
        let useroY = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        //计算距离
        let y = -(ScreenHeight - useroY.origin.y)
        
        //更新约束
    
      
      UIView.animate(withDuration: 0.25, animations: {
        self.toolBar.snp.updateConstraints({ (make) in
            make.bottom.equalTo(self.view).offset(y)
            
        })
      
        
        self.view.layoutSubviews()
      })
    }
    //一出通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //点击按钮
    func clickLeftItem(){
        
        dismiss(animated: true, completion: nil)
    }

    //导航栏控件
    func naviItem(){
       //左边关闭
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName:"", target: self, action:#selector(clickLeftItem))
        //右边
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
        //设置titleView 
        let titleLable = UILabel()
        titleLable.numberOfLines = 0
        titleLable.textAlignment = .center
        
        if let titleName = ZQUserAccountViewModel.shared.userAccount?.name {
            
            let titleText = "发布微博\n\(titleName)"
            titleLable.text = titleText
            let stringM = NSMutableAttributedString(string: titleText)
            //用户名取值范围
            let range = (titleText as NSString ) .range(of: titleName)
            
            //修改文本
            stringM.addAttributes([NSFontAttributeName : UIFont.boldSystemFont(ofSize: 12),NSForegroundColorAttributeName : UIColor.orange], range: range)
            
            //文本赋值
            titleLable.attributedText = stringM
            
        }else{
            
            titleLable.text = "发布微博"
            
        }
        titleLable.sizeToFit()
        self.navigationItem.titleView = titleLable
  
    }
    
    //添加照片选择器
    func addPicturController(){
        
        //要加载一个课控制器的姿势图
        self.addChildViewController(self.collectron)
        
        
        
        self.view.addSubview(collectron.view)
        
        //y约束
        collectron.view.snp.makeConstraints { (make) in
            
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3*2)
        }
        
        
        
    }
    
    
    
    
    
    //textView
    lazy var textView : UITextView = {
        
       let textV = UITextView()
        textV.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight / 3)
        
        textV.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        
        textV.font = UIFont.boldSystemFont(ofSize: 16)
        //代理
        textV.delegate = self
        
        textV.keyboardDismissMode = .onDrag
        textV.alwaysBounceVertical = true
        
        
        return textV
    }()
    //站位文本
    lazy var textlable : UILabel = {
        
       let lable = UILabel(title: "我是波波,我为自己代言", fontSize: 16, textColor: UIColor.gray)
        
        
        return lable
    }()
    //toolBar
    lazy var  toolBar : UIStackView =  {
        
        let toolBar = UIStackView()
 
        //方向 
        toolBar.axis = .horizontal
        
        //填充方式
        toolBar.distribution = .fillEqually
        
        
       return toolBar
       
    }()
    
    lazy var collectron :  ZQPictureCollectionController = {
        
        let flowLaYout =  UICollectionViewFlowLayout()
        flowLaYout.itemSize = CGSize(width: itmeWith, height: itmeWith)
        flowLaYout.minimumLineSpacing = PicMargin
        flowLaYout.minimumInteritemSpacing = PicMargin
        
        flowLaYout.sectionInset = UIEdgeInsets(top: PicMargin, left: PicMargin, bottom: 0, right: PicMargin)
        

        let collection = ZQPictureCollectionController(collectionViewLayout: flowLaYout)
        
        
        
        return collection
    }()
    
    
    
    //发送按钮
    lazy var rightBarButtonItem : UIBarButtonItem = {
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        //设置字体颜色
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.gray, for: .normal)

        //添加
        btn.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
      return barButtonItem
    }()
    
  }
//分类的代理方法
extension ZQComposeTableViewController : UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        
        
        rightBarButtonItem.isEnabled = textView.hasText
        
        //隐藏的时候用Hiddeb
        textlable.isHidden = textView.hasText
        
    }


     }
 //分类
       extension ZQComposeTableViewController {
        
        func showToolbar(){
            

            
           self.view.addSubview(toolBar)
            
        
      //设置约束'
            toolBar.snp.makeConstraints { (make) in
                make.left.right.bottom.equalTo(self.view)
                make.height.equalTo(40)
            }

            
            //添加按钮
            let imageNames = ["compose_toolbar_picture",
                              "compose_mentionbutton_background",
                              "compose_trendbutton_background",
                              "compose_emoticonbutton_background",
                              "compose_add_background"]
            
            for (index,imageName) in imageNames.enumerated() {
   
                let btn = UIButton()
                
                btn.setImage(UIImage(named:imageName), for: .normal)
                
                btn.backgroundColor = UIColor.white
                
                btn.sizeToFit()
                //添加到toolBar
                toolBar.addArrangedSubview(btn)
                
                btn.addTarget(self, action: #selector(toolBarButtonDidClick(btn:)), for: .touchUpInside)
                
                btn.tag = index + baseTag
            }
            

            
        }
   

        //添加约束
        func textViewcLable(){
            
            self.view.addSubview(textView)
            //添加占位文本
            self.textView.addSubview(textlable)
            
            textView.snp.makeConstraints { (make) in
                make.top.left.right.equalTo(self.view)
                //添加高度约束
                make.height.equalTo(ScreenHeight / 3)
            }
            textlable.snp.makeConstraints { (make) in
                
                make.top.equalTo(textView).offset(8)
                make.left.equalTo(textView).offset(5)
            }
            
        }
        

    }
    

